sed Commands

SED is used for finding, filtering, text substitution, replacement and text manipulations like insertion, deletion search etc. It’s a one of the powerful utility offered by Linux/Unix systems. We can use sed with regular expressions. I hope atleast you have the basic knowledge about Linux regular expressions.

Basic text substitution using ‘sed’

echo "Bash Scripting Language" | sed 's/Bash/Perl/'

sed 's/Sunday/Sunday is holiday/' weekday.txt

python.txt

Python is a very popular language.

Python is easy to use. Python is easy to learn.

Python is a cross-platform language

Replace first occurrence of a text in a particular line

sed '2s/Python/perl/' python.txt

Replace all instances of a text in a particular line of a file using ‘g’ option

sed '2 s/Python/perl/g' python.txt

Replace the second occurrence only of a match on each line

sed 's/Python/perl/g2' python.txt


Sed Command

To display few lines in the file

Sed –n 2,3p test.txt


To display file content except few line in the file

Sed 2,3p test.txt


To delete an nth line in the file

Sed 3d test.txt

Sed $d test.txt


To search and replace an string with other string in the file

First occurance of word in every line

Sed ‘/s/hello/Hello’ test.txt


All occurance of word in the every line

Sed ‘s/hello/Hello/g’ test.txt


Second occurrence of word

Sed ‘s/Hello/hello/2’ test.txt


Second occurance of word in every line

Sed ‘s/Hello/hello/2g’ test.txt


Only particular line, replace the word

Sed ‘2-3 s/Hello/hello/’ test.txt


Multiple sed commands

Sed -e ‘s/hello/Hello/g’ –e ‘s/Hello/hello’ test.txt



No comments:

Post a Comment